package utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

/**
 * 本地缓存的工具类
 * Author：Wbin
 * E_mail：atwbin@163.com
 */

public class LocalCacheUtils {
    private static final String MNT_SDCARD_QPMALL = "/mnt/sdcard/qp_mallshop_one/";

    /**
     * 根据url将图片保存到本地
     * @param url
     * @param bitmap
     */
  public void  putBitmap2Local(String url,Bitmap bitmap){
      //文件需要MD5加密
      try {
          String fileName = MD5Encoder.encode(url);
          File file = new File(MNT_SDCARD_QPMALL,fileName);
          File parentFile = file.getParentFile();
          if (!parentFile.exists()){
              parentFile.mkdirs();
          }
          FileOutputStream fos = new FileOutputStream(file);
          bitmap.compress(Bitmap.CompressFormat.PNG,100,fos);
          fos.flush();
          fos.close();
      } catch (Exception e) {
          e.printStackTrace();
      }
  }

    /**
     *根据url得到图片
     * @param url
     * @return
     */
    public Bitmap getBitmapFromUrl(String url){
        try {
            String fileName = MD5Encoder.encode(url);
            File file = new File(MNT_SDCARD_QPMALL,fileName);
            if (file.exists()){
                FileInputStream fis = new FileInputStream(file);
                Bitmap bitmap = BitmapFactory.decodeStream(fis);
                fis.close();
                return bitmap;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
